<?php

namespace App\Task\Stat;

use App\Model\PayOrder;
use App\Model\Stat\StatInviteInfo;
use App\Model\UserProfile;
use Hyperf\Crontab\Annotation\Crontab;

/**
 * 邀请关系信息
 * @Crontab(name="StatInviteInfoTask", rule="25,55 *\/1 * * *", callback="execute", memo="邀请关系信息", singleton=false)
 */
class StatInviteInfoTask
{
    public function execute()
    {
        log_info(__CLASS__ . "==Start==" . date('Y-m-d H:i:s'));
        //邀请列表
        $where = [
            ['created_at', '>', '2021-10-01'],
            ['invite_code', '<>', '']
        ];
        $inviteList = UserProfile::where($where)->pluck('invite_code', 'user_id')->toArray();
        $info = [];
        foreach ($inviteList as $invitedId => $inviteProfileId) {
            if (!isset($info[$inviteProfileId])) $info[$inviteProfileId] = [];
            $info[$inviteProfileId][] = $invitedId;
        }
        $inviters = array_keys($info);
        $inviters = UserProfile::whereIn('user_profile_id', $inviters)->pluck('user_id', 'user_profile_id')->toArray();
        foreach ($info as $profileId => $invitedIds) {
            $inviterId = $inviters[$profileId] ?? 0;
            if (!$inviterId) continue;
            //计算充值人数
            StatInviteInfo::updateOrCreate(['invite_id' => $inviterId], [
                'invited_num' => count($invitedIds),
                'recharge_rmb' => PayOrder::getRechargeCoin($invitedIds, '', '', '', 'rmb') / 100,
            ]);
        }
    }
}
